<template>
  <div>
    <el-card style="overflow:visible;">
      <el-form :model="form" size="mini" label-position="top" ref="form">
        <el-row :gutter="10">
          <el-col :lg="4" :md="6">
            <el-form-item label='机构号'>
              <select-tree :branch="form.BRANCHNAME" @getBranchName="getBranch"></select-tree>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="6">
            <el-form-item label="质检人员ID" prop="USERNUM">
              <el-input v-model="form.USERNUM" placeholder="请输入质检人员ID"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="4" :md="6">
            <el-form-item label="质检人员姓名" prop="SPECIALATTRIBUTE">
              <el-input v-model="form.SPECIALATTRIBUTE" placeholder="请输入质检人员姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :lg='8' :md='12' class="searchBtnMarginTop" :offset="4">
            <el-button type="primary" icon='el-icon-search' size='mini' @click="querySeat">查询</el-button>
            <el-button type='warning' size='mini' icon='el-icon-refresh' @click="resetForm('form')">重置</el-button>
            <el-button type="primary" size="mini" icon='el-icon-plus' @click="addDialog" :disabled="this.USERNUM.length==0">手动分发</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <el-col>
          <el-table :data="tableData" style="margin-top:20px;"  ref="multipleTable" @selection-change="changeFun" @select="selectMemoryFn"
              @select-all="selectAll">
            <el-table-column type="selection" width="55" :selectable="checkboxInit"></el-table-column>
            <el-table-column label="质检人员ID" prop="USERNUM" align="center"></el-table-column>
            <el-table-column label="机构号" prop="BRANCHNUM" align="center"></el-table-column>
            <el-table-column label="质检人员姓名" prop="USERNAME" align="center"></el-table-column>
            <el-table-column label="性别" prop="GENDER" align="center" :formatter="dataFormat"></el-table-column>
            <el-table-column label="联系方式" prop="CONTACTNUM" align="center"></el-table-column>
            <!-- <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="修改" placement="top">
                  <el-button type="text" style="margin-left:0px" @click="editDialog(scope.row)">
                    <i class="el-icon-edit-outline"></i>
                  </el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="删除" placement="top">
                  <el-button type="text" style="margin-left:0px" @click="dictionaryEdit('D',scope.row)">
                    <i class="el-icon-delete"></i>
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column> -->
          </el-table>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-pagination style="text-align: right; margin-top:20px;" :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize" @size-change="handleInSizeChange" @current-change="handleInCurrentChange"
            :current-page="currpage" background layout="sizes, total, prev, pager, next, jumper" :total="tableTotal">
          </el-pagination>
        </el-col>
      </el-row>
    </el-card>
    <!-- 新增和编辑Dialog -->
    <el-dialog :title="dialogTitle" v-if="editIsShow" :visible.sync="editIsShow" :close-on-click-modal="false"
      @close="closeDialog('ruleForm')" @open="openDialog" width="60%">
      <el-card>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" size="small">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-form-item label="开始日期" prop="BEGINDATE">
                <el-date-picker size="mini" style="width:100%;" v-model="ruleForm.BEGINDATE" type="date"
                  value-format="yyyyMMdd" :clearable='false' placeholder="开始日期" :picker-options="pickerOptionsStart"
                  @change="changeStart">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束日期" prop="ENDDATE">
                <el-date-picker style="width:100%;" size="mini" v-model="ruleForm.ENDDATE" type="date"
                  value-format="yyyyMMdd" placeholder="结束日期" :picker-options="pickerOptionsEnd" @change="changeEnd"
                  :clearable='false'>
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="采集批次号">
                <el-select v-model="ruleForm.BATCHNO" placeholder="请选择批次号" @change="changeBatch" size="mini">
                  <el-option v-for="item in batchOption" :key="item.BATCHNO" :label="item.BATCHNO" :value="item.BATCHNO"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="未分配的任务总数">
                <el-input v-model.trim="ruleForm.samplTotal" size="mini" maxlength="20" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="质检开始日期" prop="TASKBEGINDATE">
                <el-date-picker size="mini" style="width:100%;" :disabled="ruleForm.BATCHNO==''||ruleForm.BATCHNO==undefined" v-model="ruleForm.TASKBEGINDATE" type="date"
                  value-format="yyyyMMdd" :clearable='false' placeholder="质检开始日期" :picker-options="pickerOptionsStartTask"
                  @change="changeStartTask">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="质检结束日期" prop="TASKENDDATE">
                <el-date-picker style="width:100%;" size="mini" :disabled="ruleForm.BATCHNO==''||ruleForm.BATCHNO==undefined" v-model="ruleForm.TASKENDDATE" type="date"
                  value-format="yyyyMMdd" placeholder="质检结束日期" :picker-options="pickerOptionsEndTask" @change="changeEndTask"
                  :clearable='false'>
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="平均每人处理数量" prop="NUM">
                <el-input v-model.trim="ruleForm.NUM" size="mini" maxlength="20" :disabled="this.ruleForm.samplTotal=='0'"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog('ruleForm')" size="mini">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')" size="mini">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import request from "@/common/utils/requestQC";
  import selectTree from "@/components/selectTree5/";
  import getGlobalParams from "@/common/utils/getGlobalParams";
  import querySeat from '@/message/QCManage/taskAssignment/taskAssignment/querySeat';
  import mnualTask from '@/message/QCManage/taskAssignment/taskAssignment/mnualTask';
  import querySampling from '@/message/QCManage/taskAssignment/taskAssignment/querySampling';
  export default {
    components: {
      selectTree
    },
    data() {
      let numCheck = (rule, value, callback) => {
        if (!Number(value)) {
          callback(new Error("请输入数字值"));
        } else if(Number(value)*Number(this.USERNUM.length)>this.ruleForm.samplTotal){
          callback(new Error("质检人员分配的总条数(质检人员人数*每个质检人员处理数据条数)大于任务总数"));
        }else{
          callback();
        }
      };
      return {
        batchOption: [],//批次号
        pickerOptionsStart: {
          disabledDate: (time) => {
            return time.getTime() > Date.now()
          }
        },
        pickerOptionsEnd: {
          disabledDate: (time) => {
            return time.getTime() > Date.now()
          }
        },
        pickerOptionsStartTask: {
          disabledDate: (time) => {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        pickerOptionsEndTask: {
          disabledDate: (time) => {
            return time.getTime() < Date.now() - 8.64e7
          }
        },
        form:{
          BRANCHNUM:'',
          BRANCHNAME:'',
          USERNUM: '',
          SPECIALATTRIBUTE: '',
        },
        tableTotal: 1,
        currpage: 1,
        pageSize: getGlobalParams.get("PageSize"),
        ruleForm: {
          NUM:'',
          BEGINDATE: this.getDay(-30),
          ENDDATE: this.getDay(0),
          BATCHNO: '',
          samplTotal: '',
          TASKBEGINDATE: '',
          TASKENDDATE: ''

        },
        rules: {
          NUM: [
            {require: false,validator: numCheck,trigger: "blur"}
          ],
        },
        dialogTitle: '',
        editIsShow: false,
        tableData: [],
        multipleSelection: [], // 选中的数据二维数组
        USERNUM: [], // 选中的数据USERNUM数组
        checkList: [], //选中数列
        "GENDER":{
          "0":"男",
          "1":"女",
        }
      }
    },
    watch: {
      tableData (oldVal, newVal) { // 监听数据变化，然后执行分页记忆自动选中回调
        this.$nextTick(() => {
          this.selectMemoriedDataFn();
        })
      },
    },
    mounted() {
      this.querySeat();
      // this.querySampling();
    },
    methods: {
      changeBatch(val){
        this.ruleForm.samplTotal = ''
        let obj = this.batchOption.find((currentValue,index)=>{
          let num = ''
          if(currentValue.BATCHNO == val){
            num = currentValue.NUM
          } 
          return currentValue 
        })
        this.ruleForm.samplTotal = obj.NUM
      },
      // 获取当天前一天
      getDay(day) {
        var dd = new Date();
        dd.setDate(dd.getDate() + day);
        var y = dd.getFullYear();
        var m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
        var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
        return y + "" + m + "" + d;
      },
      //  开始日期
      changeStart() {
        this.pickerOptionsEnd = Object.assign({}, this.pickerOptionsEnd, {
          disabledDate: (time) => {
            if (this.ruleForm.BEGINDATE) {
              return time.getTime() < Date.parse(this.ruleForm.BEGINDATE.slice(0, 4) + '-' + this.ruleForm
                .BEGINDATE.slice(4, 6) +
                '-' + this.ruleForm.BEGINDATE.slice(6, 8)) - 8.64e7 || time.getTime() > Date.now();
            } else {
              return time.getTime() > Date.now();
            }
          }
        })
        this.querySampling()
      },
      // 结束日期
      changeEnd() {
        this.pickerOptionsStart = Object.assign({}, this.pickerOptionsStart, {
          disabledDate: (time) => {
            if (this.ruleForm.ENDDATE) {
              return time.getTime() > Date.parse(this.ruleForm.ENDDATE.slice(0, 4) + '-' + this.ruleForm
                .ENDDATE
                .slice(4, 6) + '-' +
                this.ruleForm.ENDDATE.slice(6, 8)) || time.getTime() > Date.now();
            } else {
              return time.getTime() > Date.now();
            }
          }
        })
        this.querySampling()
      },
      //  任务开始日期
      changeStartTask() {
        this.pickerOptionsEndTask = Object.assign({}, this.pickerOptionsEndTask, {
          disabledDate: (time) => {
            if (this.ruleForm.TASKBEGINDATE) {
              return time.getTime() < Date.parse(this.ruleForm.TASKBEGINDATE.slice(0, 4) + '-' + this.ruleForm
                .TASKBEGINDATE.slice(4, 6) +
                '-' + this.ruleForm.TASKBEGINDATE.slice(6, 8)) - 8.64e7 || time.getTime() < Date.now() - 8.64e7;
            } else {
              return time.getTime() < Date.now() - 8.64e7;
            }
          }
        })
      },
      // 任务结束日期
      changeEndTask() {
        this.pickerOptionsStartTask = Object.assign({}, this.pickerOptionsStartTask, {
          disabledDate: (time) => {
            if (this.ruleForm.TASKENDDATE) {
              return time.getTime() > Date.parse(this.ruleForm.TASKENDDATE.slice(0, 4) + '-' + this.ruleForm
                .TASKENDDATE
                .slice(4, 6) + '-' +
                this.ruleForm.TASKENDDATE.slice(6, 8)) || time.getTime() < Date.now() - 8.64e7;
            } else {
              return time.getTime() < Date.now() - 8.64e7;
            }
          }
        })
      },
      checkboxInit(row,index){
        if (this.checkList.indexOf(row.USERNUM)!=-1) 
          return false;//不可勾选
        else
          return true;//可勾选
      },
      changeFun(val) {
        this.$nextTick(() => {
          let USERNUM = []
          this.multipleSelection.forEach(L => L.forEach(M => USERNUM.push(M.USERNUM)))
          this.USERNUM = USERNUM;
        })
      },
      selectAll (selection) { // 全选切换方法
        if (selection.length) { // 全选
          this.multipleSelection[this.currpage-1] = selection
        } else { // 全不选
          this.multipleSelection[this.currpage-1] = []
        }
      },
      selectMemoryFn (val, row) { // 设置分页记忆二位数组方法
        // 注意：val 传过来默认为数组类型 ，row 为 Object（当前选择数据对象）
        let currentArr = this.multipleSelection[this.currpage-1] // 当前分页对应数组
        if (!currentArr) {
          this.multipleSelection[this.currpage-1] = val // 不存在这个二维数组，则创建这个二位数组
        } else { // 存在
          if (val.includes(row)) { // 选中
            this.multipleSelection[this.currpage-1] = val
          } else { // 取消
            for(var i=0;i<currentArr.length;i++){
              if(currentArr[i]){
                if(currentArr[i].USERNUM == row.USERNUM){
                  delete currentArr[i];
                  break;
                }
              }
            }
            // delete currentArr[currentArr.indexOf(row)]
          }
        }
      },
      selectMemoriedDataFn () { // 分页记忆自动选中方法
        let currentArr = this.multipleSelection[this.currpage-1]  // 当前分页对应被选中数据
        if (currentArr && currentArr.length) { // 存在则继续执行
          let tempRowsIDs = this.tableData.map(L => L.USERNUM) // 当前分页被选中数据的id集合
          currentArr.forEach((item, index) => { // 遍历当前分页被选中数据
            if (tempRowsIDs.includes(item.USERNUM)) { // id匹配上，则选中
              this.$refs.multipleTable.toggleRowSelection(this.tableData[tempRowsIDs.indexOf(item.USERNUM)])
            }
          })
        }
      },
      getBranch(data){
        this.form.BRANCHNUM = data.BRANCHNO
        this.form.BRANCHNAME= data.BRANCHNAME
      },
      resetForm(formName) { //重置查询表单
        this.$refs["" + formName].resetFields();
      },
      // 查询质检人员
      async querySeat() {
        let resBody = new querySeat();
        resBody.data.USERNUM = this.form.USERNUM;
        resBody.data.BRANCHNUM = this.form.BRANCHNUM;
        resBody.data.USERNAME = this.form.SPECIALATTRIBUTE;
        resBody.data.CurrPage = this.currpage;
        resBody.data.PageRowNum = this.pageSize;
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.tableData = response.BODY.RSPSTRUCT;
          this.tableTotal = response.BODY.TotalRowNum;
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      // 未分配的任务总数查询
      async querySampling() {
        this.batchOption = []
        this.ruleForm.samplTotal = ''
        this.ruleForm.BATCHNO = ''
        let resBody = new querySampling();
        resBody.data.BEGINDATE = this.ruleForm.BEGINDATE
        resBody.data.ENDDATE = this.ruleForm.ENDDATE
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.batchOption = response.BODY.RSPSTRUCT
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      // 编辑
      async dictionaryEdit() {
        let resBody = new mnualTask();
        resBody.data.QUALITER = this.USERNUM.join(',');
        resBody.data.NUM = this.ruleForm.NUM;
        resBody.data.TASKBEGINDATE = this.ruleForm.TASKBEGINDATE;
        resBody.data.TASKENDDATE = this.ruleForm.TASKENDDATE;
        let response = await request(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.closeDialog('ruleForm');
          this.$message({
            type: "success",
            message: '手工分配成功'
          })
          this.querySampling()
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
        }
      },
      //前端分页
      handleInCurrentChange(val) {
        this.currpage = val;
        this.querySeat();
      },
      handleInSizeChange(val) {
        this.pageSize = val;
        this.querySeat();
      },
      addDialog() {
        this.editIsShow = true;
        this.dialogTitle = '手工分配';
        this.operation = 'add';
        this.querySampling();
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if((Number(this.ruleForm.NUM)*Number(this.USERNUM.length))>this.ruleForm.samplTotal){
              this.$message({
                type: "error",
                message: "质检人员分配的总条数(质检人员人数*每个质检人员处理数据条数)大于任务总数"
              })
              return;
            }
            this.dictionaryEdit();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      openDialog() {
        if (this.$refs['ruleForm'] != undefined) {
          this.$refs['ruleForm'].clearValidate();
        }
      },
      closeDialog(formName) {
        this.editIsShow = false;
        this.ruleForm={
            NUM:'',
            BEGINDATE: this.getDay(-30),
            ENDDATE: this.getDay(0),
            BATCHNO: '',
            samplTotal: '',
          }
      },
      dataFormat(row, column) {
        //枚举设备形式
        if (column.property == "GENDER")
          return this.GENDER[row[column.property]];
      },
    }
  }

</script>
